package com.zito.health.service.impl;

import com.zito.health.entity.User;
import com.zito.health.mapper.UserMapper;
import com.zito.health.service.MailService;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.mail.javamail.MimeMessageHelper;
import org.springframework.stereotype.Service;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.Context;

import javax.mail.MessagingException;
import javax.mail.internet.MimeMessage;
import java.util.Calendar;
import java.util.Date;
import java.util.UUID;

@Service
public class MailServiceImpl implements MailService {

    @Autowired
    private JavaMailSender mailSender;
    @Autowired
    private UserMapper userMapper;

    /**
     * 用来发送模版邮件
     */
    @Autowired
    private TemplateEngine templateEngine;

    @Value("${spring.mail.username}")
    private String from;

    @Override
    public Integer send(String subject,User user) {
        Integer res=200;//200成功
        user = userMapper.selectOne(user);
        if(user==null){
            return 300;//登录名和邮箱不匹配
        }

        String verificationCode = UUID.randomUUID().toString().toUpperCase().split("-")[0];
        user.setVerificationCode(verificationCode);
        user.setCodeTime(new Date());
        userMapper.updateByPrimaryKey(user);

        Context context = new Context();
        context.setVariable("code", verificationCode);
        String emailContent = templateEngine.process("mail", context);

        MimeMessage message = mailSender.createMimeMessage();
        MimeMessageHelper helper = null;
        try {
            helper = new MimeMessageHelper(message, true);
            helper.setFrom("济南市卫生科技网<"+from+">");
            helper.setTo(user.getEmail());
            helper.setSubject(subject);
            helper.setText(emailContent, true);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        mailSender.send(message);
        return res;
    }

    @Override
    public Integer modifyPwd(User user) {
        String pwd = user.getPassword();
        User u=new User();
        u=user;
        u.setPassword(null);
        u = userMapper.selectOne(user);
        if(u==null){
            return 300;//验证码已失效
        }
        Calendar c = Calendar.getInstance();
        long now = c.getTimeInMillis();
        c.setTime(u.getCodeTime());
        long lastly = c.getTimeInMillis();
        if((now - lastly) >= 600000){//10分钟
            return 300;//验证码已失效
        }

        User usr=new User();
        usr.setPassword(DigestUtils.md5Hex(pwd.trim()));
        usr.setUserid(u.getUserid());
//        userMapper.updateByPrimaryKey(usr);
        usr.setEdittime(new Date());
        userMapper.updateByPrimaryKeySelective(usr);
        return 200;
    }
}
